(() => {

    // 原版：作者：Luuxcyzz 链接：https://ld246.com/article/1741694005802，感谢分享~
    // chuchen接力版：
    // V0.1:增加了默认折叠，优化了部分css，增强部分易用性，对移动端进行适配，增加了编辑按钮，可调用【集成编辑环境插件】，IEE，思源里的vscode。
    // V0.2:稍稍提升交互体验，修复了部分bug。
    //待增强功能：
    // 2. 可能通过自定义属性增加对标题和折叠状态的持久化保存，但感觉不太必要~
    // 3. 暗黑主题的兼容，我不怎么用所以就懒得写了，有需要的话可以自行修改css。
    // 4. 如果发现展开后代码块行号堆叠，建议设置取消自动换行的设置，原因不明，但不关键。在【集成编辑环境插件】alt+z 可自动换行。

    const config = {
        defaultTitle: "代码块",
        defaultCollapsed: true, // 新增：默认折叠状态
        arrowExpandedHTML: '<svg class="code-arrow" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M8.59 16.59L13.17 12L8.59 7.41L10 6L16 12L10 18L8.59 16.59Z"></path></svg>',
        arrowCollapsedHTML: '<svg class="code-arrow" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M8.59 16.59L13.17 12L8.59 7.41L10 6L16 12L10 18L8.59 16.59Z"></path></svg>',
        fullscreenHTML: '<svg class="code-fullscreen" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"></path></svg>',
        exitFullscreenHTML: '<svg class="code-fullscreen" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"></path></svg>',
        editHTML: '<svg class="code-edit" width="20" height="20" viewBox="0 0 24 24" fill="currentColor"><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"></path></svg>',
        // 动态提示文本
        expandTitle: "展开",
        collapseTitle: "折叠",
        fullscreenTitle: "全屏显示代码",
        exitFullscreenTitle: "退出全屏\n快捷键ESC",
        editTitle: "编辑",
        headerMinWidth: 100,
        collapseAnimation: true,
        animationDuration: 300,
    };
    function addStyles() {
        const styles = `
            .code-block-header {
                height: 25px; 
                display: flex;
                align-items: center;
                padding: 4px 4px;
                cursor: pointer;
                background-color: var(--b3-code-block-bg);
                color: var(--b3-protyle-inline-code-color);
                border-bottom: 1px solid rgba(127, 127, 127, 0.2);
                font-size: 13px;
                font-family: var(--b3-font-family-code);
                position: relative;
                padding-left: 100px;
                z-index: 1;
            }
            
            .code-block-header:hover {
                z-index: 10;
            }
            
            /* 移动端样式 */
            @media (max-width: 768px) {
                .code-block-header {
                    padding-left: 60px;
                }
                
            .code-block[data-fullscreen="true"] {
                position: fixed !important;
                top: 0 !important;
                left: 0 !important;
                width: 100vw !important;
                height: 100vh !important;
                z-index: 9999 !important; /* 大幅提高z-index值 */
                background-color:rgb(195, 194, 194) !important;
                display: flex !important;
                flex-direction: column !important;
                overflow: hidden !important;
                margin: 0 !important;
                padding: 0 !important;
                transform: none !important;
                box-sizing: border-box !important;
                will-change: transform;
                contain: layout style paint;
            }
            }
            

  
            .code-block-title {
                margin-left: 8px;
                flex-grow: 1;
                line-height: 1.5;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                order: 2;
            }
  
            .code-arrow {
                width: 30px;
                height: 30px;
                transition: transform 0.2s ease;
                order: 1;
                margin-right: 5px;
                cursor: grab;
                z-index: 12;
                position: relative;
                background: transparent;
                border: none;
                outline: none;
            }
            
            .code-arrow:hover {
                background-color: rgba(0, 0, 0, 0.1);
                border-radius: 4px;
            }
  
            .code-edit-button {
                width: 35px;
                height: 35px;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: help;
                opacity: 0.4;
                transition: all 0.3s ease;
                order: 3;
                margin-left: 5px;
                margin-right: 5px;
                z-index: 12;
                position: relative;
                background: transparent;
                border: none;
                outline: none;
            }
            
            .code-edit-button:hover {
                background-color: rgba(0, 0, 0, 0.1);
                border-radius: 4px;
                opacity: 1;
                transform: scale(1.1);
            }
            
            .code-fullscreen-button {
                width: 35px;
                height: 35px;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: zoom-in;
                opacity: 0.7;
                transition: all 0.3s ease;
                order: 4;
                margin-left: auto;
                margin-right: 60px;
                z-index: 12;
                position: relative;
                background: transparent;
                border: none;
                outline: none;
            }
            
            .code-fullscreen-button:hover {
                background-color: rgba(0, 0, 0, 0.1);
                border-radius: 4px;
            }
  
            .code-fullscreen-button:hover {
                opacity: 1;
                transform: scale(1.1);
            }
  
            .code-fullscreen {
                width: 24px;
                height: 24px;
            }
  
            .code-block-title:empty:before {
                content: "${config.defaultTitle}";
                opacity: 0.6;
            }
  
            .code-block[data-collapsed="true"] .code-block-header .code-arrow {
                transform: rotate(0deg);
            }
  
            .code-block[data-collapsed="false"] .code-block-header .code-arrow {
                transform: rotate(90deg);
            }
  
            .code-block[data-collapsed="true"] .code-block-header {
                border-bottom: none;
                opacity: 0.8;
            }
  
            .code-block-title:focus {
                outline: none;
                border-bottom: 1px dotted var(--b3-protyle-inline-code-color);
                cursor: text;
            }
  
            .code-block[data-collapsed="true"] .hljs {
                display: none;
            }
  
            .code-block[data-fullscreen="true"] {
                position: fixed !important;
                top: 0 !important;
                left: 0 !important;
                width: 100vw !important;
                height: 100vh !important;
                z-index: 14 !important;
                background-color:rgb(189, 189, 168) !important;
                display: flex !important;
                flex-direction: column !important;
                overflow: hidden !important;
                margin: 0 !important;
                padding: 0 !important;
                transform: none !important;
                box-sizing: border-box !important;
            }
  
            .code-block[data-fullscreen="true"] .hljs {
                flex-grow: 1;
                overflow: hidden !important;
                max-height: none !important;
                display: block !important;
                height: auto !important;
                opacity: 1 !important;
                background-color:rgba(199, 202, 185, 0.9) !important;
                padding: 16px !important;
                z-index: 10!important;
            }
  
            .code-block[data-fullscreen="true"] .code-block-header {
                position: sticky;
                top: 0;
                z-index: 12 !important;
                justify-content: center;
            }
            
            .code-block[data-fullscreen="true"] .code-edit-button {
                position: absolute !important;
                right: 100px !important;
                top: 5% !important;
                margin-left: 0 !important;
                margin-right: 0 !important;
                z-index: 25 !important;
                opacity: 0.8 !important;
                cursor: help !important;
                pointer-events: auto !important;
                border-radius: 4px !important;
                padding: 4px !important;
            }
            
            .code-block[data-fullscreen="true"] .code-edit-button:hover {
                transform: scale(1.1) !important;
            }
            
            .code-block[data-fullscreen="true"] .code-fullscreen-button {
                position: absolute !important;
                right: 60px !important;
                top: 5% !important;

                margin-left: 0 !important;
                margin-right: 0 !important;
                z-index: 25 !important;
                opacity: 1 !important;
                cursor: zoom-out !important;
                pointer-events: auto !important;
                border-radius: 4px !important;
                padding: 4px !important;
            }
            
            .code-block[data-fullscreen="true"] .code-fullscreen-button:hover {
                transform:scale(1.1) !important;
            }
        `;
        const styleEl = document.createElement('style');
        styleEl.innerHTML = styles;
        document.head.appendChild(styleEl);
    }
    function createCodeBlockHeader(codeBlock) {
        if (codeBlock.querySelector('.code-block-header')) {
            return;
        }
        const header = document.createElement('div');
        header.className = 'code-block-header protyle-custom';

        header.innerHTML = config.arrowExpandedHTML;

        // 注意：折叠箭头是SVG，无法直接设置title，改为在header上设置title
        header.title = config.defaultCollapsed ? config.expandTitle : config.collapseTitle;

        const title = document.createElement('div');
        title.className = 'code-block-title';
        title.contentEditable = 'true';
        title.spellcheck = false;

        const language = getCodeBlockLanguage(codeBlock);
        if (language) {
            title.textContent = language;
        }

        header.appendChild(title);

        const fullscreenButton = document.createElement('div');
        fullscreenButton.className = 'code-fullscreen-button';
        fullscreenButton.innerHTML = config.fullscreenHTML;
        fullscreenButton.title = config.fullscreenTitle;

        header.appendChild(fullscreenButton);

        // 创建编辑按钮（移动端不显示）
        const editButton = document.createElement('div');
        editButton.className = 'code-edit-button';
        editButton.innerHTML = config.editHTML;
        editButton.title = config.editTitle;

        // 移动端隐藏编辑按钮
        if (isMobile()) {
            editButton.style.display = 'none';
        }

        header.appendChild(editButton);

        header.addEventListener('click', (e) => {
            // 禁用标题编辑时的折叠
            if ((e.target === title && document.activeElement === title) ||
                fullscreenButton.contains(e.target) ||
                editButton.contains(e.target)) {
                return;
            }

            // 计算点击位置，如果在预留的语言标签区域内（左侧10px），则不触发折叠
            const rect = header.getBoundingClientRect();
            const clickX = e.clientX - rect.left;
            if (clickX < 10) {
                return; // 在语言标签区域内，不触发折叠功能
            }

            toggleCodeBlock(codeBlock);
        });

        title.addEventListener('click', (e) => {
            e.stopPropagation();
        });

        title.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                e.preventDefault();
                title.blur();
            }
        });

        fullscreenButton.addEventListener('click', (e) => {
            e.stopPropagation();
            toggleFullscreen(codeBlock, fullscreenButton);
        });

        editButton.addEventListener('click', (e) => {
            e.stopPropagation();
            openCodeBlockInNewWindow(codeBlock);
        });

        codeBlock.insertBefore(header, codeBlock.firstChild);

        // 根据配置设置默认状态
        const defaultState = config.defaultCollapsed ? 'true' : 'false';
        codeBlock.setAttribute('data-collapsed', defaultState);
        codeBlock.setAttribute('data-fullscreen', 'false');

        // 如果默认折叠，立即隐藏代码内容
        if (config.defaultCollapsed) {
            const hljs = codeBlock.querySelector('.hljs');
            if (hljs) {
                hljs.style.display = 'none';
            }
        }
    }

    function toggleFullscreen(codeBlock, button) {
        const isFullscreen = codeBlock.getAttribute('data-fullscreen') === 'true';
        const hljs = codeBlock.querySelector('.hljs');

        if (isFullscreen) {
            codeBlock.setAttribute('data-fullscreen', 'false');
            // 直接替换整个按钮内容
            button.innerHTML = config.fullscreenHTML;
            button.title = config.fullscreenTitle;


            if (codeBlock._wasCollapsedBeforeFullscreen) {

                if (hljs) {
                    hljs.style.display = '';
                    hljs.style.maxHeight = '';
                    hljs.style.height = '';
                    hljs.style.opacity = '';
                    hljs.style.overflow = '';


                    delete hljs.dataset.animating;
                }


                setTimeout(() => {
                    codeBlock.setAttribute('data-collapsed', 'true');
                    if (hljs) {
                        hljs.style.display = 'none';
                    }
                    delete codeBlock._wasCollapsedBeforeFullscreen;
                }, 50);
            }

            // 恢复移动端时从 body 挪回原位置
            if (codeBlock._fsPlaceholder) {
                try {
                    const placeholder = codeBlock._fsPlaceholder;
                    if (placeholder.parentNode) {
                        placeholder.parentNode.insertBefore(codeBlock, placeholder);
                        placeholder.remove();
                    }
                } catch (_) {}
                delete codeBlock._fsPlaceholder;
            }
            if (codeBlock._originalBodyOverflow !== undefined) {
                document.body.style.overflow = codeBlock._originalBodyOverflow;
                delete codeBlock._originalBodyOverflow;
            }

            if (window._scrollPositionBeforeFullscreen !== undefined) {
                window.scrollTo(0, window._scrollPositionBeforeFullscreen);
                delete window._scrollPositionBeforeFullscreen;
            }
        } else {
            window._scrollPositionBeforeFullscreen = window.scrollY;

            if (codeBlock.getAttribute('data-collapsed') === 'true') {
                codeBlock._wasCollapsedBeforeFullscreen = true;
                codeBlock.setAttribute('data-collapsed', 'false');

                if (hljs) {

                    hljs.style.display = 'block';
                    hljs.style.maxHeight = 'none';
                    hljs.style.height = 'auto';
                    hljs.style.opacity = '1';
                    hljs.style.overflow = 'auto';


                    if (hljs.dataset.animating === 'true') {
                        delete hljs.dataset.animating;
                    }
                }
            }

            // 移动端且在容器块中：将代码块移到 body，避免容器的 transform/overflow 截断 fixed 定位
            if (isMobile() && isInsideContainerBlock(codeBlock)) {
                const placeholder = document.createElement('div');
                placeholder.style.display = 'none';
                codeBlock.parentNode && codeBlock.parentNode.insertBefore(placeholder, codeBlock.nextSibling);
                document.body.appendChild(codeBlock);
                codeBlock._fsPlaceholder = placeholder;
                // 锁定 body 滚动，防止背景滚动
                if (codeBlock._originalBodyOverflow === undefined) {
                    codeBlock._originalBodyOverflow = document.body.style.overflow || '';
                }
                document.body.style.overflow = 'hidden';
            }

            codeBlock.setAttribute('data-fullscreen', 'true');
            // 直接替换整个按钮内容
            button.innerHTML = config.exitFullscreenHTML;
            button.title = config.exitFullscreenTitle;

            setTimeout(() => {
                if (hljs) {
                    hljs.scrollTop = 0;
                }
            }, 0);
        }
    }

    function getCodeBlockLanguage(codeBlock) {
        const hljsElement = codeBlock.querySelector('.hljs');
        if (!hljsElement) return null;

        const classes = hljsElement.className.split(' ');
        for (const cls of classes) {
            if (cls !== 'hljs' && cls.length > 0) {
                return cls;
            }
        }

        return null;
    }
    function toggleCodeBlock(codeBlock) {
        if (codeBlock.getAttribute('data-fullscreen') === 'true') {
            return;
        }

        const isCollapsed = codeBlock.getAttribute('data-collapsed') === 'true';
        const hljs = codeBlock.querySelector('.hljs');

        if (!hljs) return;

        if (hljs.dataset.animating === 'true') {
            return;
        }

        hljs.dataset.animating = 'true';

        hljs.style.transition = 'none';
        codeBlock.classList.remove('animate');

        if (isCollapsed) {
            hljs.style.display = 'block';
            hljs.style.height = '0px';
            hljs.style.overflow = 'hidden';
            hljs.style.opacity = '0';

            const targetHeight = hljs.scrollHeight;

            const heightAnimation = hljs.animate([
                { height: '0px', opacity: 0 },
                { height: targetHeight + 'px', opacity: 1 }
            ], {
                duration: 250,
                easing: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
                fill: 'forwards'
            });

            heightAnimation.onfinish = () => {
                hljs.style.height = '';
                hljs.style.overflow = '';
                hljs.style.opacity = '';
                hljs.style.transition = '';

                delete hljs.dataset.animating;
            };
        } else {
            const startHeight = hljs.offsetHeight;
            hljs.style.height = startHeight + 'px';
            hljs.style.overflow = 'hidden';

            hljs.animate([
                { opacity: 1 },
                { opacity: 0 }
            ], {
                duration: 120,
                easing: 'ease-out',
                fill: 'forwards'
            });

            setTimeout(() => {
                const heightAnimation = hljs.animate([
                    { height: startHeight + 'px' },
                    { height: '0px' }
                ], {
                    duration: 180,
                    easing: 'cubic-bezier(0.4, 0.0, 0.2, 1)',
                    fill: 'forwards'
                });

                heightAnimation.onfinish = () => {
                    hljs.style.display = 'none';

                    hljs.style.height = '';
                    hljs.style.opacity = '';
                    hljs.style.overflow = '';
                    hljs.style.transition = '';

                    delete hljs.dataset.animating;
                };
            }, 70);
        }

        codeBlock.setAttribute('data-collapsed', !isCollapsed);

        // 更新header的标题
        const header = codeBlock.querySelector('.code-block-header');
        if (header) {
            header.title = !isCollapsed ? config.expandTitle : config.collapseTitle;
        }
    }
    function processCodeBlocks(element) {
        const codeBlocks = element.querySelectorAll('.code-block:not([data-processed="true"])');
        codeBlocks.forEach(codeBlock => {
            createCodeBlockHeader(codeBlock);
            codeBlock.setAttribute('data-processed', 'true');
        });
    }
    function observeCodeBlockAddition(container) {
        const observer = new MutationObserver(mutations => {
            mutations.forEach(mutation => {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeType === Node.ELEMENT_NODE) {
                            // 直接处理代码块
                            if (node.classList && node.classList.contains('code-block') && !node.hasAttribute('data-processed')) {
                                createCodeBlockHeader(node);
                                node.setAttribute('data-processed', 'true');
                            }

                            // 处理包含代码块的容器
                            if (node.querySelectorAll) {
                                const codeBlocks = node.querySelectorAll('.code-block:not([data-processed="true"])');
                                codeBlocks.forEach(codeBlock => {
                                    createCodeBlockHeader(codeBlock);
                                    codeBlock.setAttribute('data-processed', 'true');
                                });
                            }
                        }
                    });
                }
            });
        });

        observer.observe(container, {
            childList: true,
            subtree: true,
            attributes: false,
            attributeOldValue: false
        });

        return observer;
    }
    function setupKeyboardHandlers() {
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                const fullscreenCodeBlock = document.querySelector('.code-block[data-fullscreen="true"]');
                if (fullscreenCodeBlock) {
                    const fullscreenButton = fullscreenCodeBlock.querySelector('.code-fullscreen-button');
                    if (fullscreenButton) {
                        e.preventDefault();
                        e.stopPropagation();
                        toggleFullscreen(fullscreenCodeBlock, fullscreenButton);
                        return false;
                    }
                }
            }
        }, true);
    }
    function waitForElement(selector) {
        return new Promise(resolve => {
            if (document.querySelector(selector)) {
                return resolve(document.querySelector(selector));
            }

            const observer = new MutationObserver(() => {
                if (document.querySelector(selector)) {
                    observer.disconnect();
                    resolve(document.querySelector(selector));
                }
            });

            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
        });
    }
    function isMobile() {
        return !!document.getElementById("sidebar");
    }
    async function init() {
        addStyles();
        setupKeyboardHandlers();

        // 等待主容器加载
        const container = await waitForElement(isMobile() ? '.protyle-content' : '.layout__center');

        // 处理现有的代码块
        processCodeBlocks(document.body);

        // 设置全局观察器，监听整个文档的变化
        observeCodeBlockAddition(document.body);

        // 同时保持原有的 protyle 观察逻辑
        observeProtyleAddition(container, protyles => {
            protyles.forEach(protyle => {
                if (!protyle.classList.contains('protyle')) {
                    protyle = protyle.closest('.protyle');
                }

                if (protyle) {
                    processCodeBlocks(protyle);
                }
            });
        });

        // 定期检查遗漏的代码块（兜底机制）
        setInterval(() => {
            const unprocessedBlocks = document.querySelectorAll('.code-block:not([data-processed="true"])');
            if (unprocessedBlocks.length > 0) {
                unprocessedBlocks.forEach(codeBlock => {
                    createCodeBlockHeader(codeBlock);
                    codeBlock.setAttribute('data-processed', 'true');
                });
            }
        }, 1000);
    }
    function observeProtyleAddition(container, callback) {
        const observer = new MutationObserver(mutations => {
            const protyles = [];

            mutations.forEach(mutation => {
                if (mutation.type === 'childList') {
                    mutation.addedNodes.forEach(node => {
                        if (node.nodeType === Node.ELEMENT_NODE) {
                            if (node.classList &&
                                (node.classList.contains('protyle') ||
                                    node.classList.contains('protyle-content'))) {
                                protyles.push(node);
                            }
                        }
                    });
                }
            });

            if (protyles.length > 0) {
                callback(protyles);
            }
        });

        observer.observe(container, {
            childList: true,
            subtree: true
        });

        return observer;
    }


// 编辑按钮功能：模拟点击菜单打开集成编辑环境 - 无鼠标移动版
function openCodeBlockInNewWindow(codeBlock) {
    try {
        // 优先选择 protyle-action 区域（语言标签区域）
        const protoyleAction = codeBlock.querySelector('.protyle-action');
        const targetElement = protoyleAction || codeBlock;
        
        // 添加临时的CSS样式来隐藏菜单
        const styleId = 'temp-menu-hider';
        let styleElement = document.getElementById(styleId);
        
        if (!styleElement) {
            styleElement = document.createElement('style');
            styleElement.id = styleId;
            document.head.appendChild(styleElement);
        }
        
        // 使用CSS来隐藏所有菜单，这是最可靠的方式
        styleElement.textContent = `
            #commonMenu, .b3-menu, .b3-menu__submenu {
                display: none !important;
                visibility: hidden !important;
                opacity: 0 !important;
                position: fixed !important;
                left: -9999px !important;
                top: -9999px !important;
                pointer-events: none !important;
            }
        `;
        
        setTimeout(() => {
            // 模拟右键点击目标元素
            const rightClickEvent = new MouseEvent('contextmenu', {
                bubbles: true,
                cancelable: true,
                view: window,
                button: 2,
            });
            
            targetElement.dispatchEvent(rightClickEvent);
            
            // 等待菜单数据加载
            setTimeout(() => {
                // 查找"集成编辑环境"菜单项
                const menuItems = document.querySelectorAll('#commonMenu .b3-menu__item');
                let integratedEditItem = null;
                
                for (const item of menuItems) {
                    const label = item.querySelector('.b3-menu__label');
                    if (label && label.textContent.includes('集成编辑环境')) {
                        integratedEditItem = item;
                        break;
                    }
                }
                
                if (integratedEditItem) {
                    // 点击"集成编辑环境"展开子菜单
                    integratedEditItem.click();
                    
                    setTimeout(() => {
                        moveMouse()
                        // 查找"使用新窗口打开"选项
                        const submenuItems = document.querySelectorAll('.b3-menu__submenu .b3-menu__item');
                        for (const item of submenuItems) {
                            const label = item.querySelector('.b3-menu__label');
                            if (label && label.textContent.includes('使用新窗口打开')) {
                                // 临时恢复菜单项的交互能力
                                const originalStyle = item.style.cssText;
                                item.style.pointerEvents = 'auto';
                                
                                // 点击打开新窗口
                                item.click();
                                
                                // 恢复样式
                                item.style.cssText = originalStyle;
                                
                                // 清理临时样式
                                setTimeout(() => {
                                    if (styleElement && document.head.contains(styleElement)) {
                                        document.head.removeChild(styleElement);
                                    }
                                }, 100);
                                return;
                            }
                        }
                        
                        // 清理临时样式
                        if (styleElement && document.head.contains(styleElement)) {
                            document.head.removeChild(styleElement);
                        }
                    }, 100);
                } else {
                    // 清理临时样式
                    if (styleElement && document.head.contains(styleElement)) {
                        document.head.removeChild(styleElement);
                    }
                }
            }, 150);
        }, 50);
        
    } catch (error) {
        // console.error('打开代码块编辑窗口失败:', error);
        // 确保清理临时样式
        const styleElement = document.getElementById('temp-menu-hider');
        if (styleElement && document.head.contains(styleElement)) {
            document.head.removeChild(styleElement);
        }
    }
}

    // 移动鼠标到指定位置的函数
    function moveMouse (x=0, y=0) {
        // 创建一个鼠标移动事件
        const mousemoveEvent = new MouseEvent('mousemove', {
            bubbles: true,
            cancelable: true,
            view: window,
            clientX: x,
            clientY: y
        });

        // 触发鼠标移动事件
        document.body.dispatchEvent(mousemoveEvent);
    }

    // 判断是否在容器块（如列表项等）中的辅助函数
    function isInsideContainerBlock(element) {
        if (!element) return false;
        // 列表、列表项、引用、超级块、表格等常见容器
        const selector = '.li, [data-type="NodeListItem"], [data-type="NodeList"], [data-type="NodeBlockquote"], [data-type="NodeSuperBlock"], [data-type="NodeTable"]';
        return !!element.closest(selector);
    }


    init();
})();

